import dayjs from './dayjs.min.js'
import api from '../api/index'
import constant from './constant'
import model from '../plugins/model'
import { isNull } from '../utils/index'
import { config } from '../config'


//登录
export function checkLogin(){
	return new Promise((resolve, reject)=>{
    wx.$showLoading()
		const token = wx.getStorageSync(constant.TOKEN)
    const expiresTime = wx.getStorageSync(constant.EXPIRES_TIME)
    console.log('checkLogin token:' + token + '    expiresTime: '+ expiresTime)
    if(isNull(token)){
      console.log('token空未登录')
      logout()
      resolve(constant.LOGIN_NOT_LOGIN)
      return;
    }

    //刷新
    const now = dayjs().valueOf();
    const timeDiff = Number(expiresTime) - now;
    if(timeDiff || timeDiff>0){
      // 少于3小时刷新token 3 * 60 * 60 * 1000
      if (timeDiff < 3 * 60 * 60 * 1000) {
        refreshToken().then((res) => {
          wx.$hideLoading()
          if(res === 0){
            resolve(constant.LOGIN_SUCCESS)
          }else{
            logout()
            resolve(constant.LOGIN_NOT_LOGIN)
          }
          return
        })
      }
      wx.$hideLoading()
      resolve(constant.LOGIN_SUCCESS)
      return
    }else{
      console.log('失效时间' + timeDiff + '删除token')
      logout()
      wx.$hideLoading()
      resolve(constant.LOGIN_NOT_LOGIN)
      return
    }
  })
}

export function getUserInfo(){
  return new Promise((resolve, reject)=>{
    api.login.userInfo().then((res)=>{
      wx.$showLoading()
      if(wx.$isNull(res.avatar) && wx.$isNull(res.sex)){
        if(config().regUserBaisInfo){
          wx.$hideLoading()
          wx.redirectTo({
            url: '/pages/login/regBasicInfo/index',
          })
          return
        }
      }else{
        wx.setStorageSync(constant.USER_INFO, res)
        wx.$hideLoading()
        resolve(true)
        return
      }
    })
  })
}


export const logout= ()=>{
	api.login.logout().then(()=>{
		wx.removeStorage({
			key: constant.TOKEN
		})
		wx.removeStorage({
			key: constant.EXPIRES_TIME
		})
	}).catch(error => {
		model.fail(error)
	})


}

/**
 * 刷新token
 */
export const refreshToken = ()=>{
  // 调用刷新接口，
  console.log("刷新token");
  return new Promise(function(resolve, reject) {
		api.login.refreshToken().then((res)=>{
      wx.setStorageSync(constant.EXPIRES_TIME, dayjs().valueOf() + res.expiresIn * 1000)
      resolve(0)
      return
		}).catch((e)=>{
      resolve(-1)
      return
		})
  })
}

// 登录按钮登录
export function loginOpenId(isReg){
  return new Promise((resolve, reject)=>{
    checkLogin().then(cRes=>{
      if(cRes == constant.LOGIN_SUCCESS){
        resolve({ code: constant.LOGIN_SUCCESS })
        return
      }else{
        wx.login({
          success: (wxRes) => {
            wx.$showLoading()
            api.login.getToken(isReg, wxRes.code, 'wx').then((res)=>{
              // accessToken为空 即为未注册用户
              if(wx.$isNull(res.accessToken)){
                wx.$hideLoading()
                
                resolve({code:constant.LOGIN_NOT_REGISTER})
                return
              }
              wx.setStorageSync(constant.TOKEN, res.accessToken)
              wx.setStorageSync(constant.EXPIRES_TIME, dayjs().valueOf() + res.expiresIn * 1000)
              wx.$hideLoading()
              resolve({code:constant.LOGIN_SUCCESS})
              return
            })
          },
          fail: function(err){
            model.fail(err)
            wx.$hideLoading()
            resolve({code: 500, msg: err})
          }
        })
      }
    })



  })
}
